package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"goods-master/cache"
	"goods-master/model"
	"strconv"
	"time"
)

func GoodAdd(c *gin.Context) {
	goodNo := c.PostForm("goodNo")
	goodName := c.PostForm("goodName")
	data := model.Good{
		GoodNo:   goodNo,
		GoodName: goodName,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func OrderAdd(c *gin.Context) {
	orderNo := c.PostForm("orderNo")
	orderName := c.PostForm("orderName")
	orderPrice, _ := strconv.Atoi(c.PostForm("orderPrice"))
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	data := model.Order{
		OrderNO:    orderNo,
		OrderName:  orderName,
		OrderPrice: orderPrice,
		Gid:        gid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var data []model.OrderList
	redis_list_key := "list_" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		model.DB.Table("goods").
			Select(
				"orders.id AS ID",
				"orders.order_no AS OrderNo",
				"orders.order_name AS OrderName",
				"orders.order_price AS OrderPrice",
				"goods.good_name AS GoodName",
			).
			Joins("LEFT JOIN orders ON orders.gid = goods.id").
			Debug().Offset(offset).Limit(size).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &data)
	}
	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表成功",
		"data":  data,
		"total": total,
	})
	return
	/*SELECT
	orders.id AS ID,
	  orders.order_no AS OrderNo,
	  orders.order_name AS OrderName,
	  orders.order_price AS OrderPrice,
	  goods.good_name AS GoodName,
	  goods.good_no AS GoodNo
	FROM
	  goods
	  LEFT JOIN orders ON orders.gid = goods.id*/

}
func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	var data model.Order
	redis_detail_key := "detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if result == "" {
		model.DB.Where("id=?", id).First(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": data,
	})
	return
}
